package handler;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * Reads/Writes unencrypted, uncompressed files from the filesystem.
 * 
 * @author Jared Schlicht
 */
public class XMLDAO implements NotebookDAO {
    private String filename;
    private XMLHandler xmlHandler;
    
    /**
     * Constructs a new XMLDAO object for the specified filename.
     * 
     * @author Jared Schlicht
     * @param filename filename of the file to parse or write to
     */
    public XMLDAO(String filename) {
        this.filename = filename;
        this.xmlHandler = new XMLHandler();
    }
    
    /**
     * Constructs a new XMLDAO object for the specified file object.
     * 
     * @author Jared Schlicht
     * @param file a file object representing the file that will be read/written to
     */
    public XMLDAO(java.io.File file) {
        this(file.getName());
    }
    
    /**
     * Gets a list of equations from the file
     * @return List of notebook equations or null if an error occurred
     */
    @Override
    public List<EquateNode> getEquations() {
        InputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(this.filename);
            return this.xmlHandler.getEquations(fileInputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();                    
                }
            } catch (IOException e) {
                e.printStackTrace();
            }            
        }
    }

    /**
     * Saves the equations to the file as regular (unencrypted, uncompressed) XML
     * @author Jared Schlicht
     */
    @Override
    public void saveEquations(List<EquateNode> notebookEquations) {
        OutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(this.filename);
            this.xmlHandler.saveEquations(notebookEquations, fileOutputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();                    
                }
            } catch (IOException e) {
                e.printStackTrace();
            }            
        }
    }
}
